from faker import Faker
import random
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from data_mock.utils import FileUtil, MysqlUtils_AI
fake = Faker('zh_CN')

# ========== 癌症相关配置 ==========
CANCER_TYPES = {
    'C34.90': {'name': '肺恶性肿瘤', 'symptoms': ['咳嗽', '咯血', '胸痛', '呼吸困难']},
    'C16.9': {'name': '胃恶性肿瘤', 'symptoms': ['上腹痛', '恶心呕吐', '黑便', '食欲减退']},
    'C18.9': {'name': '结肠恶性肿瘤', 'symptoms': ['腹痛', '便血', '排便习惯改变', '体重下降']},
    'C50.919': {'name': '乳腺恶性肿瘤', 'symptoms': ['乳房肿块', '乳头溢液', '皮肤凹陷', '腋窝淋巴结肿大']},
    'C61': {'name': '前列腺恶性肿瘤', 'symptoms': ['排尿困难', '尿频', '血尿', '骨盆疼痛']}
}


# ========== 生成函数 ==========
def generate_admission_records():
    sql_statements = []
    record_sn_counter = 10001  # 记录流水号计数器

    # 生成30天的数据
    for day in generate_day_range("2025-08-01", "2025-08-30"):
        records_per_day = 6 if datetime.strptime(day, "%Y-%m-%d").day % 2 else 8

        for i in range(records_per_day):
            # 选择随机癌症类型
            cancer_code, cancer_info = random.choice(list(CANCER_TYPES.items()))

            # 生成患者基本信息
            patient_id = f"PT{random.randint(1000, 9999)}"
            visit_sn = f"VIS{random.randint(1000, 9999)}"
            record_sn = f"ADM{record_sn_counter}"
            record_sn_counter += 1

            # 生成生命体征
            systolic = random.randint(90, 180)
            diastolic = systolic - random.randint(20, 50)

            # 构建数据字典
            data = {
                'patient_id': patient_id,
                'visit_sn': visit_sn,
                'record_sn': record_sn,
                'record_datetime': fake.date_time_between(
                    start_date=datetime.strptime(day, "%Y-%m-%d"),
                    end_date=datetime.strptime(day, "%Y-%m-%d") + timedelta(days=1)
                ).strftime('%Y-%m-%d %H:%M:%S'),
                'medical_record_no': f"MR{random.randint(100000, 999999)}",
                'inpatient_no': f"IP{random.randint(100000, 999999)}",
                'hospitalization_times': str(random.randint(1, 5)),
                'kps_score': str(random.randint(40, 90)),
                'ecog_score': str(random.randint(0, 3)),

                # 文书内容
                'chief_complaint': generate_chief_complaint(cancer_info['symptoms']),
                'current_medhistory': generate_current_medhistory(cancer_code, cancer_info['name']),
                'past_medhistory': generate_past_medhistory(),
                'personal_medhistory': generate_personal_history(),
                'marriage_birth_history': generate_marriage_history(),
                'family_history': generate_family_history(),
                'menstrual_history': generate_menstrual_history() if random.choice([True, False]) else None,

                # 生命体征
                'systolic_pressure': str(systolic),
                'diastolic_pressure': str(diastolic),
                'respiratory_rate': str(random.randint(12, 24)),
                'body_temperature': str(round(random.uniform(36.5, 38.5), 1)),
                'heart_rate': str(random.randint(60, 120)),
                'height': str(random.randint(150, 190)),
                'weight': str(random.randint(40, 100)),
                'body_surface_area': str(round(random.uniform(1.5, 2.2), 2)),

                # 检查信息
                'physical_exam': generate_physical_exam(cancer_info['name']),
                'special_exam': generate_special_exam(cancer_info['name']),
                'auxiliary_exam': generate_auxiliary_exam(),

                # 诊断信息
                'admission_maindiag_code1': cancer_code,
                'admission_maindiag_name1': cancer_info['name'],
                'admission_diag_code2': random.choice(['I10', 'E11.9', 'E78.5']),
                'admission_diag_name2': random.choice(['高血压', '2型糖尿病', '高脂血症']),

                # 系统字段
                'record_status': 1,
                'yy_upload_status': 0,
                'yy_etl_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'yy_batch_time': day,
                'yy_record_batch_id': f"BATCH{day}_{i}"
            }

            sql = generate_sql('b05_1', data)
            sql_statements.append(sql)

    return sql_statements


# ========== 文书内容生成函数 ==========
def generate_chief_complaint(symptoms):
    duration = f"{random.randint(1, 12)}个月"
    main_symptom = random.choice(symptoms)
    return f"患者因'{main_symptom}{duration}'入院"


def generate_current_medhistory(code, name):
    onset_time = f"{random.randint(1, 12)}个月前"
    progress = random.choice(["逐渐加重", "反复发作"])
    treatment = random.choice(["未行特殊治疗", "曾于外院就诊"])
    return f"{onset_time}无明显诱因出现{name}相关症状，{progress}，{treatment}。"


def generate_past_medhistory():
    diseases = ["高血压", "糖尿病", "冠心病", "慢性胃炎"]
    selected = random.sample(diseases, random.randint(0, 2))
    return "既往有" + "、".join(selected) + "病史。" if selected else "否认既往重大疾病史。"


def generate_personal_history():
    habits = ["吸烟", "饮酒", "长期熬夜"]
    selected = random.sample(habits, random.randint(0, 2))
    return "有" + "、".join(selected) + "。" if selected else "无特殊不良生活习惯。"


def generate_marriage_history():
    status = random.choice(["已婚", "离异", "丧偶"])
    children = f"，育有{random.randint(0, 3)}子{random.randint(0, 3)}女" if status == "已婚" else ""
    return f"{status}{children}。"


def generate_family_history():
    cancers = ["肺癌", "胃癌", "肠癌", "乳腺癌"]
    selected = random.sample(cancers, random.randint(0, 2))
    return "家族中有" + "、".join(selected) + "病史。" if selected else "否认家族肿瘤病史。"


def generate_menstrual_history():
    return f"初潮{random.randint(12, 16)}岁，周期{random.randint(25, 35)}天，经期{random.randint(3, 7)}天，末次月经：{fake.date_this_year().strftime('%Y-%m-%d')}。"


# ========== 检查信息生成函数 ==========
def generate_physical_exam(cancer_name):
    findings = {
        '肺恶性肿瘤': "双肺呼吸音粗，未闻及明显干湿啰音",
        '胃恶性肿瘤': "腹平软，上腹部轻压痛，无反跳痛",
        '结肠恶性肿瘤': "腹平软，左下腹可触及包块，轻压痛",
        '乳腺恶性肿瘤': "左乳外上象限可触及质硬包块，活动度差",
        '前列腺恶性肿瘤': "直肠指检前列腺增大，质硬，表面不平"
    }
    return findings.get(cancer_name, "神志清，精神可，心肺腹查体未见明显异常")


def generate_special_exam(cancer_name):
    findings = {
        '肺恶性肿瘤': "胸部CT示右肺上叶占位，大小约3.5cm×2.8cm",
        '胃恶性肿瘤': "胃镜示胃窦部溃疡型肿物，表面糜烂",
        '结肠恶性肿瘤': "肠镜示降结肠菜花样肿物，肠腔狭窄",
        '乳腺恶性肿瘤': "乳腺超声示左乳低回声结节，BI-RADS 4类",
        '前列腺恶性肿瘤': "前列腺MRI示外周带结节，PI-RADS 4分"
    }
    return findings.get(cancer_name, "专科查体未见明显异常")


def generate_auxiliary_exam():
    exams = [
        "血常规：WBC 6.5×10⁹/L，Hb 120g/L",
        "肝功能：ALT 35U/L，AST 28U/L",
        "肿瘤标志物：CEA 15.6ng/ml（升高）",
        "心电图：窦性心律，正常范围心电图"
    ]
    return "\n".join(random.sample(exams, random.randint(2, 4)))


# ========== 辅助函数 ==========
def generate_day_range(start_date, end_date):
    start = datetime.strptime(start_date, "%Y-%m-%d")
    end = datetime.strptime(end_date, "%Y-%m-%d")
    delta = end - start
    return [(start + timedelta(days=i)).strftime("%Y-%m-%d") for i in range(delta.days + 1)]


def generate_sql(table, data):
    columns = []
    values = []
    for k, v in data.items():
        columns.append(f"`{k}`")
        if v is None:
            values.append("NULL")
        elif isinstance(v, (int, float)):
            values.append(str(v))
        else:
            escaped_value = str(v).replace("'", "''")
            values.append(f"'{escaped_value}'")
    return f"INSERT INTO `{table}` ({', '.join(columns)}) VALUES ({', '.join(values)});"

# ========== 执行生成 ==========
if __name__ == "__main__":
    print("开始生成入院记录数据...")
    records = generate_admission_records()
    # 写入数据库
    MysqlUtils_AI.insert_data_to_hub(records, 'b05_1')